package com.burns.leetcode.d2t;

public class Main {
    public static void main(String[] args) {
        ListNode l1 = new ListNode();
        initL1(l1);
        ListNode l2 = new ListNode();
        initL2(l2);
        ListNode listNode = addTwoNumbers(l1, l2);
        for (ListNode node = listNode; node != null; node = node.next) {

            System.out.print(node.val+" ");
        }
    }

    private static void initL2(ListNode l2) {
        l2.val = 9;


        ListNode l22 = new ListNode(9);
        l2.next = l22;

        ListNode l23 = new ListNode(9);
        l22.next = l23;

        ListNode l24 = new ListNode(9);
        l23.next = l24;
    }

    private static void initL1(ListNode l1) {
        l1.val = 9;


        ListNode l12 = new ListNode(9);
        l1.next = l12;

        ListNode l13 = new ListNode(9);
        l12.next = l13;

        ListNode l14 = new ListNode(9);
        l13.next = l14;

        ListNode l15 = new ListNode(9);
        l14.next = l15;

        ListNode l16 = new ListNode(9);
        l15.next = l16;

        ListNode l17 = new ListNode(9);
        l16.next = l17;

    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode l3 = new ListNode();
        ListNode point = l3;
        int l3Next = 0;
        while (!(l1 == null && l2 == null)) {
            int val1 = 0;
            if (l1 != null) {
                val1 = l1.val;
            }


            int val2 = 0;
            if (l2 != null) {
                val2 = l2.val;
            }

            int val3 = val1 + val2 + l3Next;
            ListNode l3NextNode = new ListNode();
            if (val3 > 9) {
                point.val = val3 % 10;
                l3Next = 1;
                l3NextNode.val = 1;

            } else {
                point.val = val3;
            }

            if (l1 != null && l1.next != null) {
                l1 = l1.next;
            } else {
                l1 = null;
            }

            if (l2 != null && l2.next != null) {
                l2 = l2.next;
            } else {
                l2 = null;
            }

            if (l1 != null || l2 != null) {
                point.next = l3NextNode;
                point = l3NextNode;
            }else {
                if(l3Next!=0){
                    point.next = l3NextNode;
                    point = l3NextNode;
                }
            }
        }
        return l3;

    }
}

class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}
